import re
import uiautomator2 as u2
import time, sys, os,io
import json
from lxml import etree
from PIL import Image
from loguru import logger
import pytesseract
import traceback
import subprocess
from PIL import ImageOps
import aircv as ac
import pyttsx3
import random
import datetime
import sqlite3
from multiprocessing import Lock,Value,Process, Manager
import tkinter as tk
from tkinter import ttk
#华为镜像源：https://repo.huaweicloud.com/repository/pypi/simple/
# python312 -m pip install -r requirements.txt -i https://repo.huaweicloud.com/repository/pypi/simple/
# 模拟器分辨率900*1600

process_list =[]  

class DevicePlayer:
    def __init__(self, device_id,device_name):
        self.process = None # 脚本进程
        self.device_id = device_id         # 模拟器编号
        self.device_name = device_name      # 模拟器名称
        self.user_name = ''      # 实际登录账号
        self.device = None      #驱动实例
        self.now_position =  None  # 当前持仓
        self.next_position = None     # 下一持仓预计
        self.contract_list = ['小恒指05','恒指05']       # 合约列表
        self.strategy_list = [{'round': 1, 'future': '小恒指','direction': '', 'num': 1}, 
                              {'round': 2, 'future': '小恒指','direction': '',  'num': 2},
                            {'round': 3, 'future': '恒指', 'direction': '', 'num': 1},
                            {'round': 4, 'future': '恒指', 'direction': '', 'num': 2}, 
                            {'round': 5, 'future': '恒指','direction': '',  'num': 4},
                            {'round': 6, 'future': '恒指', 'direction': '', 'num': 8}]
        
        
        
    def say(self, msg):
        engine = pyttsx3.init()
        engine.setProperty('voice', 'com.microsoft.speech.platform.voice.SynthesizerVoice')
        engine.setProperty('rate', 130)
        engine.setProperty('volume', 1.0)
        engine.say(msg)
        engine.runAndWait()

    def connect_device(self):
        """连接模拟器"""
        logname = self.device_id + '_log.txt'
        logname = self.device_name+'_'+ self.device_id+ '_log.txt'
        logger.add(logname, encoding="utf-8")
        logger.info('准备连接设备 %s ...' % self.device_id)
        d = u2.connect(self.device_id)
        logger.info(f'连接设备 {self.device_id} ({self.user_name}) 成功!')

        #self.login()           # 登录
        time.sleep(random.uniform(0.3, 5.5))
        #self.set_config()    # 初始配置

        self.transaction()     # 开始交易
        
        return d

    def disconnect_device(self):
        """断开与模拟器的连接"""
        global process_list
        print(f'断开设备 {self.device_id} ({self.user_name}) 进程...')
        print(f'进程列表：{process_list}')
        if self.device is not None:
            for p in process_list:
                print(f'进程名：{p.name}  进程id：{p.pid}')
                if p.name == self.device_id:
                    p.terminate()
                    process_list.remove(p)
                    logger.info(f'断开设备 {self.device_id} ({self.user_name}) 进程已终止！!')
                    logger.info(f'断开设备 {self.device_id} ({self.user_name}) 成功!') 
                    break
        else:
            print(self.device)

    
       

    def login(self):
        if self.device(text='登录交易').exists():
            
            time.sleep(0.5)
            self.device(resourceId="com.dalhwkhw.moni:id/username").set_text('S990008')
            self.device(resourceId="com.dalhwkhw.moni:id/psw").set_text('Icewxb2000')
            time.sleep(0.5)
            if not self.device(resourceId="com.dalhwkhw.moni:id/close_psw").info['checked']:
                self.device(resourceId="com.dalhwkhw.moni:id/close_psw").click()
            time.sleep(0.5)
            self.device(text='登录交易').click()
        else:
            logger.info(f'设备 {self.device_id} ({self.user_name}) 登录失败，不是登录页面!\n')

    def getStrategyinfo(self,last_position):
        """根据最后持单分析下一单策略"""
        for item in self.strategy_list:
            if last_position['future']==item['future'] and last_position['num']==item['num']:
                #找到了最后一次的平仓信息，要根据最后一次平仓信息来判断下一次持仓的策略
                if item['round']<6:
                    next_position=self.strategy_list[item['round']]
                    next_position['direction']=random.choice(['买','卖'])
                    logger.warning(f'{self.device_id}  {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}  当前分析最后持仓为：{last_position},下一步策略为：{next_position}')
                return next_position    
        return None # 没有找到对应策略
        #logger.warning(f'{self.device_id}  {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}  当前已有持仓为：{now_position},第{now_round}次')

    def checkStrategy(self,last_position):
        """检查内容是否符合策略"""
        if last_position is None:
            return None
        for item in self.strategy_list:
            if last_position['future']==item['future'] and last_position['num']==item['num']:
                #找到匹配策略
                return item
        return None # 没有找到对应策略
        






    def check_guadan(self):
        """检查挂单情况"""
        time.sleep(random.uniform(0.3, 1.5))
        logger.info(f'设备 {self.device_id} ({self.user_name}) 准备检查挂单!')
        self.device(resourceId="com.dalhwkhw.moni:id/frag_order_guadan").click()  # 点击挂单选项卡
        time.sleep(random.uniform(0.3, 1.5))
        self.device.drag(64, 1115, 776, 1115, 0.03)   # 向右滑动鼠标，显示表格最左边数据
        time.sleep(random.uniform(0.3, 1.5))
        # 判断是否有挂单
        while True:
            
            try:
                if self.device(resourceId="com.dalhwkhw.moni:id/tv_item").exists():
                    
                    hymc=self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/tv_item"]').get_text()  # 合约
                    wtj=self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/tv_item"]').get_text()   # 委托价
                    wtsl=self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/tv_item3"]').get_text()  # 委托数量
                    logger.info(f'设备 {self.device_id} ({self.user_name}) 挂单中，等待成交...')
                else:
                    logger.info(f'设备 {self.device_id} ({self.user_name}) 无挂单!')
                    return None
                time.sleep(random.uniform(2, 6))
            except Exception as e:
                logger.error(f'{self.device_id} {self.user_name}  {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}  获取挂单信息时发生错误{e}')
                self.say(f'账户 {self.user_name}  在 {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}  获取挂单信息时发生错误')
                return False
        

    def check_chicang(self):
        '''检查持仓情况'''
        
        logger.info(f'设备 {self.device_id} ({self.user_name}) 准备检查持单情况!')
        self.device(resourceId="com.dalhwkhw.moni:id/frag_order_chicang1").click()  # 点击持仓选项卡
        time.sleep(random.uniform(0.3, 1.5))
        if self.device(resourceId="com.dalhwkhw.moni:id/frag_order_chicang1").get_text() == "持仓(合计)":
            pass  # 如果是合计显示，则pass
        else:
            #不是合计显示，则点击一次，改为合计显示
            self.device(resourceId="com.dalhwkhw.moni:id/frag_order_chicang1").click()

        
        time.sleep(random.uniform(0.3, 1.5))
        self.device.drag(43, 1258, 830, 1258, 0.03)   # 向右滑动鼠标，显示表格最左边数据
        time.sleep(1)
        self.device.drag(50, 1200, 830, 1200, 0.03)   # 向右滑动鼠标，显示表格最左边数据
        time.sleep(1)
        
        if self.now_position is None:  # 无持仓标记
            if self.device(resourceId="com.dalhwkhw.moni:id/tv_itemname").exists():  
                if self.device(resourceId="com.dalhwkhw.moni:id/tv_itemname").info["text"] == "汇总(0)":        # 无持仓
                    logger.info(f'设备 {self.device_id} ({self.user_name}) 暂无持仓，转交易。')
                    return None
                else:
                    logger.info(f'设备 {self.device_id} ({self.user_name}) 有持仓，等待成交...')    #有持仓
                    time.sleep(random.uniform(2, 4))
            else:
                logger.error(f'设备 {self.device_id} ({self.user_name}) 持仓查询异常...程序退出!')
                self.say(f'账户 {self.user_name}  持仓查询异常...程序退出')
                self.disconnect_device()
                    
        if self.now_position is not None:  # 有持仓标记
            if self.device(resourceId="com.dalhwkhw.moni:id/tv_itemname").exists():  
                while True:
                    if self.device(resourceId="com.dalhwkhw.moni:id/tv_itemname").info["text"] == "汇总(0)":        # 有持仓标记实际无持仓
                        logger.info(f'设备 {self.device_id} ({self.user_name}) 有下单暂无持仓，等待持仓加载中...')
                        time.sleep(random.uniform(2, 4))
                    else:
                        logger.info(f'设备 {self.device_id} ({self.user_name}) 有持仓')    #有持仓
                        time.sleep(random.uniform(2, 4))
                        break

            else:
                logger.error(f'设备 {self.device_id} ({self.user_name}) 持仓查询异常...程序退出!')
                self.say(f'账户 {self.user_name}  持仓查询异常...程序退出')
                self.disconnect_device()

            

        # 有持仓，则继续执行
        hymc=self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/tv_itemname"]').get_text()  # 合约
        maimai=self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/tv_item2"]').get_text()  # 买入卖出
        cjsl=self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/tv_item4"]').get_text()    # 成交量

        self.device.drag(781, 1233, 358, 1233, 0.05)   # 向左滑动鼠标，显示表格右边数据
        yljc=self.device(resourceId="com.dalhwkhw.moni:id/tv_item_yingli").get_text()  # 盈利价差，点位数

        #print(hymc,maimai,cjsl,yljc)

        direction=''
        if '卖' in maimai:
            direction='卖'
        if '买' in maimai:
            direction='买'
        
        if '小恒指' in hymc:
            future='小恒指'
        else:
            future='恒指'

        num=cjsl
        logger.warning(f'{self.device_id} :   合约 ：{future}  方向：{direction}  数量：{num}')
         
        now_position={'direction': direction, 'future': future, 'num': int(num)}
        for item in self.strategy_list:
            if future==item['future'] and int(num)==item['num']:
                #找到了当前持仓的策略
                now_position=item
                
                
        if now_position is not None:
            self.now_position=now_position
            self.now_position['direction']=direction
            logger.warning(f'{self.device_id}  {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}  当前已有持仓策略为：{self.now_position}')  
            # 转为监控状态
            while True:
                try:
                    yljc=0
                    time.sleep(random.randint(5,15))
                    
                    yljc=self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/tv_item_yingli"]').get_text()  # 盈利价差，点位数
                    
                    print(f'{self.device_id} {self.user_name} {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}  当前持仓点差为:{yljc}')
                    if yljc is None or yljc=="" :  # 如果盈利价差为空表示持仓为空，则重新执行交易
                        self.now_position=None
                        self.next_position=None
                        #if self.check_Istransaction():  # 这个代码还有问题，时间格式不对
                        self.transaction()
                        #else:
                        #    print(f'{self.device_id} {self.user_name} {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}  当前非交易时段，等待中...')
                        

                except Exception as e:
                    logger.error(f'账户 {self.user_name}   执行持仓监控时发生错误{e}')
                    self.say(f'账户 {self.user_name}  在 {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}  执行持仓监控时发生错误!')
                    self.disconnect_device()
                    return False


        else:
            logger.error(f'{self.device_id}  {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}  当前已有持仓为：{self.device_id} :   合约 ：{future}  方向：{direction}  数量：{num},无法匹配策略)')
            self.say(f'账户 {self.user_name}  在 {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}  当前持仓无法匹配到策略，请手动处理！')
            self.disconnect_device()
            return False

    def check_username(self):
        """检查当前账户信息，判断执行权限"""
        if self.device(resourceId="com.dalhwkhw.moni:id/market_username_tv").exists():
            username = self.device(resourceId="com.dalhwkhw.moni:id/market_username_tv").get_text()
            logger.info(f'设备 {self.device_id} ({self.user_name}) 当前用户名为：{username}')
            self.user_name=username
            #self.say(f'账户 {self.user_name}  在 {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}  已登录!')
            return True
        else:
            logger.info(f'设备 {self.device_id} ({self.user_name}) 当前用户名为：未登录')
            self.disconnect_device()
            return False

    def transaction(self):
        """执行交易"""
        #if not self.check_Istransaction():
        #    # 不是交易时段，则返回
        #    return False

        if not self.device(resourceId="com.dalhwkhw.moni:id/rb_jiaoyi").exists():  # 如果没有交易按钮，则转到交易页面
            self.device(resourceId="com.dalhwkhw.moni:id/search").click()
            time.sleep(random.randint(1,3))
            self.device(resourceId="com.dalhwkhw.moni:id/my").click()
            time.sleep(random.randint(1,3))
            self.device.click(249,131)
            time.sleep(random.randint(1,3))


        self.device(resourceId="com.dalhwkhw.moni:id/rb_jiaoyi").click()   # 点击交易按钮，转到交易页面
        time.sleep(random.randint(1,3))

        if self.check_username():
            pass
        else:
            logger.warning(f'{self.device_id}  {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}  当前账户没有下单权限！')
            return False



        
        self.check_guadan() # 执行挂单检查，有挂单会转为监控状态，无挂单则返回


        if self.check_chicang() is None:  # 没有持仓
            logger.info(f'设备 {self.device_id} ({self.user_name}) 准备检查成交明细!')
            self.device(resourceId="com.dalhwkhw.moni:id/frag_order_chengjiao").click()  #                 点击成交明细选项卡
            time.sleep(random.randint(1,3))
            if self.device(resourceId="com.dalhwkhw.moni:id/frag_order_chengjiao").get_text() == "成交(明细)":
                pass  # 如果是明细显示，则pass
            else:
                #合计显示，则点击一次，改为明细显示
                self.device(resourceId="com.dalhwkhw.moni:id/frag_order_chengjiao").click()
            time.sleep(random.randint(1,3))
            # 判断是否没有当日成交明细记录
            if self.device(resourceId="com.dalhwkhw.moni:id/cjtv1_item").exists():
                if self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/cjtv1_item"]').info["text"] == "汇总(0)":
                    logger.warning(f'账号 {self.device_id} ({self.user_name}) 暂无当日成交明细!,请手动下第一单...')
                    self.disconnect_device()
                    return False
                else:
                    logger.info(f'设备 {self.device_id} ({self.user_name}) 成交明细 汇总为 {self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/cjtv1_item"]').info["text"]}')
                    #self.next_position = self.strategy_list[0]
                    #self.next_position['direction']=random.choice(['买','卖'])

                    #self.transaction_order()  # 执行交易
                    #return False
               

            self.device.drag(443, 924, 438, 1430, 0.05)   # 向下滑动鼠标，显示表格最上边数据
            time.sleep(0.5)
            self.device.drag(420, 950, 423, 1460, 0.05)   
            time.sleep(0.5)
            self.device.drag(450, 930, 455, 1450, 0.05)   
            time.sleep(0.5)



            self.device.drag(236, 1267, 851, 1267, 0.05)   # 向右滑动鼠标，显示表格最左边数据
            time.sleep(0.5)
            self.device.drag(236, 1267, 851, 1267, 0.05)   # 向右滑动鼠标，显示表格最左边数据
            time.sleep(0.5)
            self.device.drag(236, 1267, 851, 1267, 0.05)   # 向右滑动鼠标，显示表格最左边数据
            time.sleep(0.5)
          
            

                
            hymc=self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/cjtv1_item"]').get_text()  # 合约
            kp=self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/cjtv8_item"]').get_text()    # 开平
            direction=self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/cjtv2_item"]').get_text() # 买卖
            cjj=self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/cjtv3_item"]').get_text()   # 成交价
            print(1,kp)
            i=1
            if kp=='平仓':
                while True:
                    try:
                        if self.device.xpath('(//*[@resource-id="com.dalhwkhw.moni:id/cjtv8_item"])['+str(i) +']').get_text()=='平仓':    # 这个序号只是屏幕可见区域的排序，滑动屏幕后就会重新从头排，这里代码需要调整
                            _kp=self.device.xpath('(//*[@resource-id="com.dalhwkhw.moni:id/cjtv8_item"])['+str(i) +']').get_text()
                            hymc=self.device.xpath('(//*[@resource-id="com.dalhwkhw.moni:id/cjtv1_item"])['+str(i) +']').get_text()
                            direction=self.device.xpath('(//*[@resource-id="com.dalhwkhw.moni:id/cjtv2_item"])['+str(i) +']').get_text()
                            print(i,_kp,hymc,direction)
                            i=i+1
                        else:
                            break
                    except Exception as e:
                        print(e)
                        break
                print("共有平仓记录{}条".format(i-1))
                print("向右滑动屏幕")
                self.device.drag(830, 1224, 164, 1224, 0.05)  # 向左滑动鼠标，显示表格右边数据
                time.sleep(1)
                pcsl_sum=int(i-1)  # 平仓数量合计
                pcyk_sum=0

                for i in range(1,pcsl_sum+1):
                    try:
                        cjsl=int(self.device.xpath('(//*[@resource-id="com.dalhwkhw.moni:id/cjtv4_item"])['+str(i) +']').get_text())  # 成交数量
                        sxf=self.device.xpath('(//*[@resource-id="com.dalhwkhw.moni:id/cjtv6_item"])['+str(i) +']').get_text()
                        pcyk=self.device.xpath('(//*[@resource-id="com.dalhwkhw.moni:id/cjtv7_item"])['+str(i) +']').get_text()
                        cjsj=self.device.xpath('(//*[@resource-id="com.dalhwkhw.moni:id/cjtv5_item"])['+str(i) +']').get_text()
                        pcyk_sum=pcyk_sum+float(pcyk)
                        print(i,cjsl,sxf,pcyk,cjsj)
                    except Exception as e:
                        print(e)
                        self.say(f'账户 {self.user_name}  在 {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}  检查平仓结果出错，请手动处理！')
                        self.disconnect_device()
                        return False

                
               
                if '小恒指' in hymc:
                    future='小恒指'
                else:
                    future='恒指'

    
               
                
                if hymc=='' and direction=='':
                    logger.warning(f'设备 {self.device_id} ({self.user_name}) 无当日成交记录...程序退出')
                    return False

                last_position={'direction': direction, 'future': future, 'num': pcsl_sum}

                self.next_position = None
                if self.checkStrategy(last_position) is None:
                    # 平仓的策略没有匹配到，认为是出错了，返回人工处理
                    logger.error(f'{self.user_name}    平仓结果：   合约 ：{future}  方向：{direction}  数量：{pcsl_sum}, 没有匹配到策略')
                    self.say(f'账户 {self.user_name}  在 {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}  当前平仓没有匹配到策略，请手动处理！')
                    self.disconnect_device()
                    return False
                else:
                    _last_position=self.checkStrategy(last_position)
                    if _last_position['round']==6:
                        logger.info(f'{self.user_name}) 平仓结果：   合约 ：{future}  方向：{direction}  数量：{pcsl_sum} 平仓盈亏{pcyk_sum}, 已经达到最大轮次')
                        if pcyk_sum>0:
                            logger.info(f'账户 {self.user_name}  本轮进行到第6单，已盈利，重新开始下一轮')
                            self.say(f'账户 {self.user_name}  本轮进行到第6单，已盈利，重新开始下一轮')
                            self.next_position=self.strategy_list[0] # 返回第一次执行策略
                            self.next_position['direction']=random.choice(['买','卖'])
                            print(self.next_position)
                        else:
                            logger.error(f'账户 {self.user_name}   本轮进行到第6单，已亏损，请检查并上报处理，程序已停止！')
                            self.say(f'账户 {self.user_name}   本轮进行到第6单，已亏损，请检查并上报处理，程序已停止！')
                            self.disconnect_device()
                            return False
                    else:
                        if pcyk_sum>0:
                            logger.info(f'设备 {self.device_id} ({self.user_name}) {hymc} {kp} {pcsl_sum} {pcyk_sum}  平仓盈利')
                            self.next_position=self.strategy_list[0] # 返回第一次执行策略
                            self.next_position['direction']=random.choice(['买','卖'])
                            print(self.next_position)
                        else:
                            self.next_position = self.getStrategyinfo(last_position)
                            logger.info(f'设备 {self.device_id} ({self.user_name}) {hymc} {kp} {pcsl_sum} {pcyk_sum}  平仓亏损,翻倍执行')
                            print(self.next_position)

                if self.next_position  is not None:
                    self.transaction_order()
                else:
                    logger.error(f'账户 {self.user_name}  执行策略失败，请手动处理！')
                    self.say(f'账户 {self.user_name}  执行策略失败，请手动处理！')
                    self.disconnect_device()
        else:                                                                                     # 有持仓
            logger.info(f'设备 {self.device_id} ({self.user_name}) 有持仓!')
            self.check_chicang()

        return
    def remove_digits(self, s):
        # 移除字符串中的数字
        return re.sub(r'\d', '', s)
    def check_Istransaction(self):
        """判断当前时间是否允许下单"""
        time_format = '%H:%M:%S'
        today = datetime.datetime.now()
        weekday = today.weekday()
        if weekday == 5 or weekday == 6:
            return False

        # 定义开始时间和结束时间
        start_time = datetime.datetime.strptime("09:15:00", time_format)
        end_time = datetime.datetime.strptime("11:59:00", time_format)
        if datetime.datetime.now().time() < start_time or datetime.datetime.now().time() > end_time:
            #logger.info(f'设备 {self.device_id} ({self.user_name}) 不在交易时间范围内, 禁止下单')
            return False
        start_time = datetime.datetime.strptime("13:00:00", time_format)
        end_time = datetime.datetime.strptime("15:30:00", time_format)
        if datetime.datetime.now().time() < start_time or datetime.datetime.now().time() > end_time:
            #logger.info(f'设备 {self.device_id} ({self.user_name}) 不在交易时间范围内, 禁止下单')
            return False
        start_time = datetime.datetime.strptime("17:15:00", time_format)
        end_time = datetime.datetime.strptime("22:30:00", time_format)
        if datetime.datetime.now().time() < start_time or datetime.datetime.now().time() > end_time:
            #logger.info(f'设备 {self.device_id} ({self.user_name}) 不在交易时间范围内, 禁止下单')
            return False
        return True
    def transaction_order(self):
        """下单操作"""
        logger.info(f'设备 {self.device_id} ({self.user_name}) 准备下单!')
        


        #点击合约选择框
        time.sleep(random.uniform(0.3, 1.5))
        self.device(resourceId="com.dalhwkhw.moni:id/contract_name_rest").click()
        time.sleep(random.uniform(0.3, 1.5))
        
        if self.next_position['future']=='小恒指':
            if '小恒指' == self.remove_digits(self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/item_textview"]').get_text()):
                self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/item_textview"]').click()
            elif '小恒指' == self.remove_digits(self.device.xpath('(//*[@resource-id="com.dalhwkhw.moni:id/item_textview"])[2]').get_text()):
                self.device.xpath('(//*[@resource-id="com.dalhwkhw.moni:id/item_textview"])[2]').click()

        if self.next_position['future']=='恒指':
            if '恒指' == self.remove_digits(self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/item_textview"]').get_text()):
                self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/item_textview"]').click()
            elif '恒指' == self.remove_digits(self.device.xpath('(//*[@resource-id="com.dalhwkhw.moni:id/item_textview"])[2]').get_text()):
                self.device.xpath('(//*[@resource-id="com.dalhwkhw.moni:id/item_textview"])[2]').click()

        time.sleep(random.uniform(0.3, 1.5))
        #打开快速下单对话框
        self.device(resourceId="com.dalhwkhw.moni:id/stop_profit_loss").click()
        time.sleep(random.uniform(0.3, 1.5))

        #判断合约是否一致
        if self.next_position['future']!=self.remove_digits(self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/contract_name"]').get_text()):
            logger.error(f'设备 {self.device_id} ({self.user_name}) 合约不匹配!')
            return
        
        #设置方向
        if self.next_position['direction']=='买':
            if self.device(resourceId="com.dalhwkhw.moni:id/tv_buyortell").get_text()=='买入':
                pass
            else:
                self.device(resourceId="com.dalhwkhw.moni:id/tv_buyortell").click()
        elif self.next_position['direction']=='卖':
            if self.device(resourceId="com.dalhwkhw.moni:id/tv_buyortell").get_text()=='卖出':
                pass
            else:
                self.device(resourceId="com.dalhwkhw.moni:id/tv_buyortell").click()

         
        #设置手数
        self.device(resourceId="com.dalhwkhw.moni:id/et_shoushu").set_text(str(self.next_position['num']))
        time.sleep(random.uniform(0.7, 2.5))
        #设置价格
        now_price=int(self.device(resourceId="com.dalhwkhw.moni:id/tv_lastprice").get_text())
        if self.next_position['direction']=='买':
            self.device(resourceId="com.dalhwkhw.moni:id/et_price").set_text(str(now_price + 500))
        elif self.next_position['direction']=='卖':
            self.device(resourceId="com.dalhwkhw.moni:id/et_price").set_text(str(now_price - 500))
        time.sleep(random.uniform(3, 6))
        
        self.device(resourceId="com.dalhwkhw.moni:id/bt_sure").click()  # 点击确定按钮  

        # 确定下单后，要加个标记，防止重复下单，因为可能因为网络延迟，导致持仓和挂单中都无数据
        # 如果下单手数多的话，会一致在服务器排队，系统前端的持单、挂单、委托中都没有任何显示，必须得死等才行。这个问题很严重，要多测试
        self.now_position=self.next_position

                

        time.sleep(random.uniform(1, 3))
        self.device(resourceId="com.dalhwkhw.moni:id/iv_close").click()  # 关闭快速下单对话框
        time.sleep(random.uniform(2, 5))
        
        if self.check_guadan() is None:  # 检查当前挂单信息
            if self.check_chicang() is None:  # 检查当前持仓信息
                self.transaction() # 如果没有持仓，就转到交易




            
            





    def set_config(self):
        """止盈止损点位与自选合约设置"""
        while True:  # 循环取消所有自选，批量取消会导致页面无响应，所以只能一次取消一个
            #点击搜索按钮，
            self.device(resourceId="com.dalhwkhw.moni:id/search").click()
            time.sleep(1)
            # 判断是否有自选按钮出现
            if self.device(resourceId="com.dalhwkhw.moni:id/my").exists():
                logger.info(f'设备 {self.device_id} ({self.user_name}) 有自选!\n')
                self.device(resourceId="com.dalhwkhw.moni:id/my").click()
                time.sleep(1)
                screenshot = self.device.screenshot()
                screenshot = self.device.screenshot()  # 获取截图（PIL Image 对象）
                r, g, b = screenshot.getpixel((496, 133))  # 直接从 PIL Image 对象中获取像素颜色

                print(f"Color at (496, 133): RGB({r}, {g}, {b})")
                if r==68 and g==68 and b==68:  # 没有自选合约了
                    # 没有自选合约，开始选择
                    self.device(resourceId="com.dalhwkhw.moni:id/et_search").set_text(self.contract_list[0])
                    time.sleep(1)
                    self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/iv_collect"]').click()    # 点击设置为自选
                    time.sleep(1)
                    self.device(resourceId="com.dalhwkhw.moni:id/et_search").set_text(self.contract_list[1])
                    time.sleep(1)
                    self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/iv_collect"]').click()    # 点击设置为自选
                    time.sleep(1)

                    self.device(resourceId="com.dalhwkhw.moni:id/back").click()
                    break

                else:
                    logger.info(f'设备 {self.device_id} ({self.user_name}) 有自选!\n')               
                    self.device.xpath('//*[@resource-id="com.dalhwkhw.moni:id/iv_collect"]').click()    # 取消第一个自选
                    time.sleep(1)
                    self.device(resourceId="com.dalhwkhw.moni:id/back").click()
                    
                    
                            

                    
        

if __name__ == '__main__':
    root = tk.Tk()
    root.title("账号列表")
    tree_rowids=[]
    columns = ('行编号','账号','类型', '姓名','脚本','状态','账户金额','成交指数','浮动盈亏','平仓盈亏','手续费','轮/次','更新时间')
    tree = ttk.Treeview(root,columns=columns, show='headings')


    # 获取adb实际连接设备列表
    try:
        result = subprocess.run(['adb', 'devices'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        n=0
        for line in result.stdout.splitlines():
            if  'List of devices' not in line and line!="":
                print(line.split('\t'))
                device_id=line.split('\t')[0] # 截取设备号：emulator-5556  
                port=device_id.split('-')[1]  # 截取端口号  (端口号计算规则：5554+（index*2）)
                index=(int(port)-5554)/2
                p=Process()
                p = Process(target= DevicePlayer(device_id,"").connect_device, args=(p,),name=f'{device_id}')
                p.daemon = True  # 注释掉或设置为 False
                p.start()
                process_list.append(p)

                print(f'{device_id} 已连接')
                print(f'{process_list}')   
                n=n+1

    except Exception as e:
        logger.error('检索模拟器失败！')
        print(traceback.print_exc())


    
    
    
    
    root.mainloop()
        

   

   
